package com.gang.mars.redisson.Thread;

import lombok.SneakyThrows;

/**
 * 多线程，线号灯
 * */
public class Apple15SignalLamp {

    public static void main(String[] args) {

        new Apple15SignalLamp().test0();
    }

    public void test0(){
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }


    class Player extends Thread{

        TV tv;

        public Player(TV tv) {
            this.tv = tv;
        }

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                if( i%2 == 0){
                    this.tv.play("my heart go on");
                }else{
                    this.tv.play("ad is loop play...");
                }
            }
        }
    }

    class Watcher extends Thread{

        TV tv;

        public Watcher(TV tv) {
            this.tv = tv;
        }

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                tv.watch();
            }
        }
    }

    class TV{

        String voice;
        boolean flag =true;

        @SneakyThrows
        public synchronized void play(String voice){
            if (!flag){
                this.wait();
            }
            System.out.println("歌手开始演唱：" + voice);
            this.notifyAll();
            this.voice = voice;
            this.flag = !this.flag;
        }

        @SneakyThrows
        public synchronized void watch(){
            if(flag){
                this.wait();
            }

            System.out.println("观众观看表演：" + voice);
            this.notifyAll();
            this.flag = !this.flag;
        }
    }
}
